<template>
  <div>
    <el-dialog
      :title="
        type == 1 ? '添加工作站' : type == 2 ? '编辑工作站' : '审核工作站'
      "
      :visible="open"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="700px"
      append-to-body
      @close="cancel()"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="type == 1 || type == 2 ? rules : {}"
        label-width="120px"
      >
        <el-form-item label="工作站名称" prop="workstationName">
          <el-input
          v-input-restrict
            class="ml_20"
            v-if="type == 1 || type == 2"
            v-model="form.workstationName"
            maxlength="20"
            show-word-limit
            placeholder="请输入工作站名称"
          />
          <div class="ml_20" v-else>
            {{ form.workstationName }}
          </div>
        </el-form-item>
        <el-form-item label="工作站编号" prop="workstationNum">
          <el-input
          v-input-restrict
            class="ml_20"
            v-if="type == 1 || type == 2"
            maxlength="20"
            show-word-limit
            v-model="form.workstationNum"
            placeholder="请输入工作站编号"
          />
          <div class="ml_20" v-else>
            {{ form.workstationNum }}
          </div>
        </el-form-item>
        <el-form-item label="工作站封面" prop="workstationPic">
          <div class="flex ml_20" v-if="type == 1 || type == 2">
            <!-- 上传图片 -->
            <div
              v-if="form.workstationPic"
              class="upload-head"
              @click="editCropper()"
            >
              <img v-bind:src="form.workstationPic" class="cover" />
            </div>
            <div v-else class="upload-head" @click="editCropper()">
              <div>
                <img src="@/assets/images/add.png" class="add" alt="" />
              </div>
              <div style="margin-top: -10px">上传图片</div>
            </div>

            <div v-if="!form.workstationPic" class="uploadTip">
              建议图片比例16:10，支持jpg、png格式，图片小于5M
            </div>
          </div>
          <el-image
            v-else
            :src="form.workstationPic"
            :preview-src-list="[form.workstationPic]"
          >
          </el-image>
          <vuecut
            :w="320"
            :h="200"
            :url="form.workstationPic"
            @coverResult="coverResult"
            title="图片上传"
            :open.sync="vuecutshow"
          ></vuecut>
        </el-form-item>

        <el-form-item label="工作站负责人" prop="principalId">
          <el-select
            style="width: 278px"
            class="ml_20"
            v-if="type == 1 || type == 2"
            v-model="form.principalId"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in teachers"
              :key="item.teacherId"
              :label="item.name + '--' + item.teacherNum"
              :value="item.teacherId"
            />
          </el-select>
          <div class="ml_20" v-else>
            <div
              v-for="item in teachers"
              :key="item.teacherId"
              v-if="item.teacherId == form.principalId"
            >
              {{ item.name }}
            </div>
          </div>
          <el-button
            v-preventReClick
            v-if="type == 1 || type == 2"
            type="primary"
            @click="handleAddTeacher"
            style="margin-left: 15px"
            >添加教师</el-button
          >
        </el-form-item>
        <el-form-item label="工作站地址" prop="workstationAddress">
          <el-input
          v-input-restrict
            class="ml_20"
            v-if="type == 1 || type == 2"
            v-model="form.workstationAddress"
            maxlength="20"
            show-word-limit
            placeholder="请输入工作站地址"
          />
          <div class="ml_20" v-else>
            {{ form.workstationAddress }}
          </div>
        </el-form-item>
        <el-form-item label="可容纳学生数量" prop="stuNum">
          <el-input-number
            class="ml_20"
            :min="0"
            v-if="type == 1 || type == 2"
            placeholder="请输入"
            v-model="form.stuNum"
            controls-position="right"
          ></el-input-number>
          <div class="ml_20" v-else>
            {{ form.stuNum }}
          </div>
        </el-form-item>
        <el-form-item label="关联课程">
          <el-select
            style="width: 278px"
            class="ml_20"
            v-if="type == 1 || type == 2"
            v-model="form.courseIds"
            placeholder="请选择"
            multiple
            collapse-tags
          >
            <el-option
              v-for="item in courses"
              :key="item.courseId"
              :label="item.courseName"
              :value="item.courseId + ''"
            />
          </el-select>
          <el-button
            v-if="type == 1 || type == 2"
            type="primary"
            @click="form.courseIds = []"
            style="margin-left: 15px"
            >清空所有</el-button
          >
          <div class="flex ml_20" v-else>
            <div v-for="(item, index) in form.courseIds" :key="index">
              <div
                style="margin-right: 10px"
                v-if="item == item1.courseId + ''"
                v-for="(item1, index1) in courses"
                :key="index1"
              >
                {{ item1.courseName }}
              </div>
            </div>
          </div>
          <!-- <el-button v-preventReClick v-if="type == 1 || type == 2" type="primary" @click="handleAddCourse"
            style="margin-left: 15px">添加课程</el-button> -->
        </el-form-item>
        <el-form-item label="工作站描述" prop="content">
          <el-input
          v-input-restrict
            class="ml_20"
            v-if="type == 1 || type == 2"
            style="width: 80%"
            maxlength="500"
            show-word-limit
            :rows="3"
            v-model="form.content"
            type="textarea"
            placeholder="请输入工作站描述"
          />
          <div class="ml_20" v-else style="white-space: pre-wrap">
            {{ form.content }}
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="cancel">取 消</el-button>
        <el-button
          v-preventReClick
          type="primary"
          @click="submitForm"
          v-if="type == 1"
          >提交审核</el-button
        >
        <el-button
          v-preventReClick
          type="primary"
          @click="submitForm"
          v-if="type == 2"
          >确 定</el-button
        >
        <el-button
          v-preventReClick
          type="danger"
          @click="handleReject()"
          v-if="type == 3"
          >驳 回</el-button
        >
        <el-button
          v-preventReClick
          type="primary"
          @click="audit(auditStatus == 2 ? 3 : 0)"
          v-if="type == 3"
          >通 过</el-button
        >
      </div>
    </el-dialog>
    <!-- 添加教师 -->
    <addTeacher
      :open.sync="addTeacherOpen"
      :type="1"
      @refresh="getTeacher()"
    ></addTeacher>
    <!-- 驳回 -->
    <reject
      :open.sync="rejectOpen"
      :type="1"
      @refresh="reasonDiaReturn"
    ></reject>
  </div>
</template>

<script>
import {
  listPost_teacher,
  checkTeacherNum,
} from "@/api/schoolOrganization/teacher";
import { listPost_course } from "@/api/course/course";
import {
  addPost_workstation,
  updatePost_workstation,
  getPost_workstation,
} from "@/api/workstation/workstation";
import addTeacher from "@/components/addTeacher.vue";
import { getPost_school } from "@/api/schoolOrganization/schoolInfo";
import reject from "@/components/reject.vue";
export default {
  components: { reject, addTeacher },
  props: {
    open: Boolean,
    type: Number,
    id: Number,
    auditStatus: [Number, String],
  },
  data() {
    return {
      info: {},
      rejectOpen: false,
      vuecutshow: false,
      // 表单参数
      form: {
        checkStatus: undefined,
        content: undefined,
        courseIds: undefined,
        principalId: undefined,
        remark: undefined,
        schoolId: undefined,
        score: undefined,
        status: undefined,
        stuNum: undefined,
        teacherIds: undefined,
        teachingObjectives: undefined,
        uncheckReason: undefined,
        workstationAddress: undefined,
        workstationId: undefined,
        workstationName: undefined,
        workstationNum: undefined,
        workstationPic: undefined,
      },
      // 表单校验
      rules: {
        workstationName: [
          { required: true, message: "工作站名称不能为空", trigger: "blur" },
        ],
        workstationNum: [
          { required: true, message: "工作站编号不能为空", trigger: "blur" },
        ],
        workstationPic: [
          { required: true, message: "工作站封面不能为空", trigger: "blur" },
        ],
        principalId: [
          { required: true, message: "工作站负责人不能为空", trigger: "blur" },
        ],
        workstationAddress: [
          { required: true, message: "工作站地址不能为空", trigger: "blur" },
        ],
        stuNum: [
          {
            required: true,
            message: "可容纳学生人数不能为空",
            trigger: "blur",
          },
        ],
      },
      //   教师列表
      teachers: [],
      addTeacherOpen: false,
      courses: [],
    };
  },
  watch: {
    open(e) {
      if (e) {
        this.getTeacher();
        this.getCourse();
        this.getAuildInfo();
        if (this.type == 1) {
          this.reset();
        }
        if (this.type == 3 || this.type == 2) {
          this.reset();
          getPost_workstation(this.id).then((res) => {
            res.data.courseIds = res.data.courseIds
              ? res.data.courseIds.split(",")
              : [];
            if (res.data.courseList) {
              res.data.courseIds = res.data.courseList.map((item) => {
                return item.course_id;
              });
            }
            this.form = res.data;
            console.log(this.form);
          });
        }
      }
    },
  },
  mounted() {},
  methods: {
    /** 获取学校信息 */
    async getAuildInfo() {
      let res = await getPost_school();
      const { code, data } = res;
      if (code == 200) {
        this.info = data;
      }
    },
    handleReject() {
      this.rejectOpen = true;
    },
    reasonDiaReturn(e) {
      console.log("xxx");
      this.audit(4, e, true);
    },
    /* 添加教师按钮 */
    async handleAddTeacher() {
      let res = await checkTeacherNum();
      if (res.data) {
        this.addTeacherOpen = true;
      } else {
        this.$modal.msgWarning("当前已达到教师数量限制");
      }
    },
    /* 添加课程按钮 */
    handleAddCourse() {
      this.$router.push({
        path: "/course/addCourse",
        query: {
          type: "add",
        },
      });
    },
    /* 审核 */
    audit(status, reason, isReject) {
      let data = JSON.parse(JSON.stringify(this.form));
      //驳回
      if (isReject) {
        data.checkStatus = status;
        data.uncheckReason = reason;
      }
      // 通过
      else {
        //通过审核  判断是否是分院审核（auditStatus == 2）  判断审核配置是否需要学校审核(workstationNeedCheckSchool==1  需要)
        if (this.auditStatus == 2) {
          if (this.info.workstationNeedCheckSchool == 1) {
            data.checkStatus = 3;
          } else {
            data.checkStatus = 0;
          }
        } else {
          data.checkStatus = 0;
        }
      }
      data.courseIds = data.courseIds ? data.courseIds.join(",") : "";
      updatePost_workstation(data).then((response) => {
        if (isReject) {
          this.$modal.msgSuccess("驳回成功");
        } else {
          //通过审核  判断是否是分院审核（auditStatus == 2）  判断审核配置是否需要学校审核(workstationNeedCheckSchool==1  需要)
          if (this.auditStatus == 2) {
            if (this.info.workstationNeedCheckSchool == 1) {
              this.$modal.msgSuccess("审核成功，待学校审核！");
            } else {
              this.$modal.msgSuccess("审核成功！");
            }
          } else {
            this.$modal.msgSuccess("审核成功！");
          }
        }
        this.$emit("update:open", false);
        this.$emit("refresh", true);
      });
    },
    /* 获取详细信息 */
    getInfo() {},
    editCropper() {
      this.vuecutshow = true;
    },
    coverResult(e) {
      this.form.workstationPic = e;
    },
    getCourse() {
      listPost_course({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId,
      }).then((response) => {
        response.rows.courseIds = response.rows.courseIds
          ? response.rows.courseIds.split(",")
          : [];
        this.courses = response.rows;
      });
    },
    // 获取教师列表 teacherId name
    getTeacher() {
      listPost_teacher({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId,
      }).then((response) => {
        this.teachers = response.rows;
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.form));
          data.courseIds = data.courseIds ? data.courseIds.join(",") : "";
          if (this.form.workstationId != undefined) {
            if (data.status == 4) {
              data.status = 3;
            }
            updatePost_workstation(data).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.$emit("update:open", false);
              this.$emit("refresh", true);
            });
          } else {
            data.schoolId = this.$store.getters.schoolId;
            addPost_workstation(data).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.$emit("update:open", false);
              this.$emit("refresh", true);
            });
          }
        }
      });
    },
    // 表单重置
    reset() {
      this.resetForm("form");
      this.form = {
        checkStatus: undefined,
        content: undefined,
        courseIds: [],
        principalId: undefined,
        remark: undefined,
        schoolId: undefined,
        score: undefined,
        status: undefined,
        stuNum: undefined,
        teacherIds: undefined,
        teachingObjectives: undefined,
        uncheckReason: undefined,
        workstationAddress: undefined,
        workstationId: undefined,
        workstationName: undefined,
        workstationNum: undefined,
        workstationPic: undefined,
      };
    },
    cancel() {
      this.$emit("update:open", false);
      this.reset();
    },
  },
};
</script>
<style scoped lang="scss">
.uploadTip {
  line-height: 160px;
  height: 90px;
}

.upload-head {
  width: 152px;
  height: 92px;

  .add {
    width: 29px;
    height: 29px;
    margin: 20px 0 0 auto;
  }

  .cover {
    width: 150px;
    height: 90px;
  }
}

.upload-head:hover:after {
  line-height: 90px;
}
::v-deep .el-form-item__content {
  margin-left: 130px !important;
}
.ml_20 {
}
</style>
